package logic

import (
	"context"
	"io"
	"net/http"

	"gateway/internal/svc"
	"gateway/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type GatewayLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGatewayLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GatewayLogic {
	return &GatewayLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GatewayLogic) Gateway(req *types.Request) (resp *types.Response, err error) {
	// 获取原始请求路径
	path := l.ctx.Value("http_path").(string) // go-zero 会把原始 path 放在 context，或者你可以自己传入

	// 构建 user 服务 URL
	userServiceURL := "http://localhost:8888"
	targetURL := userServiceURL + path

	// 创建新请求，方法和 header 与原请求一致
	httpReq, err := http.NewRequest(http.MethodGet, targetURL, nil)
	if err != nil {
		return nil, err
	}

	// 可以根据需要拷贝 header
	httpReq.Header.Set("Content-Type", "application/json")

	// 发起请求
	httpResp, err := http.DefaultClient.Do(httpReq)
	if err != nil {
		return nil, err
	}
	defer httpResp.Body.Close()

	body, err := io.ReadAll(httpResp.Body)
	if err != nil {
		return nil, err
	}

	// 返回 user 服务响应
	return &types.Response{
		Message: string(body),
	}, nil
}
